package tree_backtrack_prune;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class 全排列_46 {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> branch = new ArrayDeque<>();
        boolean[] visited = new boolean[nums.length];
        // 使用visited全为true来判断全访问了
        dfs(nums, visited,  branch, res );
        return res;
    }

    private void dfs(int[] nums, boolean[] visited, Deque<Integer> branch, List<List<Integer>> res) {
        if(trueArray(visited)) {
            res.add(new ArrayList<>(branch));
            return;
        }
        for(int i = 0; i < nums.length; i++) {
            if(visited[i]) continue;
            visited[i] = true;
            branch.addLast(nums[i]);
            dfs(nums, visited, branch, res);
            // 每个元素都有访问不访问两种选择
            // 回溯回去 改为不访问而是先访问其他的
            branch.removeLast();
            visited[i] = false;
        }
    }

    private boolean trueArray(boolean[] arr) {
        for(boolean b : arr) {
            if(!b) return false;
        }
        return true;
    }

}
